package ru.ifmo.ipimenov.ewf_svn.standalone.dao.impl;

import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import ru.ifmo.ipimenov.ewf_svn.standalone.dao.DocumentDao;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.db.Document;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.db.User;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.db.Category;
import ru.ifmo.ipimenov.ewf_svn.standalone.util.HibernateUtil;

import java.util.List;

/**
 * @author: Ilya Pimenov
 * Scartel Starlab company
 */
public class DocumentDaoHibernate implements DocumentDao {
    /**
     * Logger for all purposes
     */
    private static Log log = LogFactory.getLog(DocumentDaoHibernate.class);

    public List<Document> load(User u) {
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        s.beginTransaction();

        List<Document> l = s.createCriteria(Document.class).add(Restrictions.eq("holder", u)).list();
        s.getTransaction().commit();

        return l;
    }

    public Document load(Integer id) {
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        s.beginTransaction();

        Document document = (Document)s.createCriteria(Document.class).add(Restrictions.eq("id", id)).uniqueResult();
        s.getTransaction().commit();

        return document;
    }

    public List<Document> load(Category c) {
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        s.beginTransaction();

        List<Document> l = s.createCriteria(Document.class).add(Restrictions.eq("category", c)).list();
        s.getTransaction().commit();

        return l;
    }

    public void save(Document d) {
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        s.beginTransaction();

        s.save(d);

        s.getTransaction().commit();
    }

    public void update(Document d) {
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        s.beginTransaction();

        s.update(d);

        s.getTransaction().commit();

    }
}
